package cn.xsly.org.service.impl;

import cn.xsly.basic.service.impl.BaseServiceImpl;
import cn.xsly.org.domain.Department;
import cn.xsly.org.mapper.DepartmentMapper;
import cn.xsly.org.service.IDepartmentService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class DepartmentServiceImpl extends BaseServiceImpl<Department> implements IDepartmentService {

  @Autowired
  private DepartmentMapper departmentMapper;

  @Transactional
    @Override
    public void add(Department department) {
        departmentMapper.save(department);
      //情况1：不选 -> parent_id=null
      //情况2：选了清空 -> parent_id=null
      //情况3：选上级部门 -> parent_id=6[上级部门]
        //如果没有选择上级部门放自己id
      if(department.getParent_id()==null){
          department.setDirPath("/"+department.getId());
      }else {
           Long parent_id= department.getParent_id();
      String parentDirPath=departmentMapper.loadById(parent_id).getDirPath();
      department.setDirPath(parentDirPath+"/"+department.getId());
      }
      departmentMapper.update(department);
    }

    @Transactional
    @Override
    public void update(Department department) {
        if(department.getParent()==null){
            department.setDirPath("/"+department.getId());
        }else{
            Long parent_id = department.getParent_id();
            String parent_dirPath = departmentMapper.loadById(parent_id).getDirPath();
            department.setDirPath(parent_dirPath+"/"+department.getId());
            //对上级部门的处理
            // /1/47/3      47
        }
        departmentMapper.update(department);
    }



    @Override
    public List<Department> deptTree() {
      //查询出所有数据
        List<Department> all=departmentMapper.loadAll();
      //把部门id和部门数据放进map中
        Map<Long, Department> map = new HashMap<>();
        for (Department department:all){
            map.put(department.getId(),department);
        }
        //前端需要得到集合的数据
        List<Department> deptTree=new ArrayList<>();
        for(Department department:all){
            //判断顶级ID
            if(department.getParent_id()==null){
                deptTree.add(department);
            }else{
                //找到当前父部门
               Long parent_id= department.getParent_id();
                //这种从数据库查询的方式，每次通过id去查询 - 查询出来映射给实体domain，
                // children集合中都会是空集合 - 没有任何数据
                //下面这种是从Map中去获取的 - 以前装进去的对象还是会存在
                Department parentDepartment = map.get(parent_id);
                parentDepartment.getChildren().add(department);
            }
        }
        return deptTree;
    }
}
